package com.platform.comm.web.results;

import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.*;
import java.util.function.Function;

/**
 * Description: Elasticsearch Search Data DTO
 *
 * @author libin created on 2019/10/30
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class EsDataJsonResult<T> extends JsonResult {

    protected T data;
    private String resourceKey;

    protected Map<String, String> mapping = new LinkedHashMap<>();
    private List<Map<String, String>> columns = new ArrayList<>();

    public EsDataJsonResult() {
        super();
    }

    /**
     * 如果data字段不为null，则应用指定mapper函数给data。<br>
     * 字段code和message将原样复制
     *
     * @return 总返回一个新的DataJsonResult，原DataJsonResult不做修改
     */
    public <U> EsDataJsonResult<U> map(Function<? super T, ? extends U> mapper) {
        Objects.requireNonNull(mapper);
        EsDataJsonResult<U> result = new EsDataJsonResult<>();
        result.copy(this);
        result.setMapping(mapping);
        result.setColumns(columns);
        result.setResourceKey(resourceKey);
        if (this.data != null) {
            result.data = mapper.apply(data);
        }
        return result;
    }

    public static <T> EsDataJsonResult<T> succeed(T data) {
        EsDataJsonResult<T> result = new EsDataJsonResult<>();
        result.setData(data);
        return result;
    }

    public void addMapping(String key, String value) {
        this.mapping.put(key, value);
    }

    public void addMapping(Map<String, String> mapping) {
        this.mapping.putAll(mapping);
    }
}
